package org.crc.myvhrb.service;

import org.crc.myvhrb.mapper.EmployeeMapper;
import org.crc.myvhrb.model.Employee;
import org.crc.myvhrb.model.RespBeanPage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * CRC
 * 2021/8/13
 */
@Service
public class EmployeeService {

    public static final Logger logger = LoggerFactory.getLogger(EmployeeService.class);

    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;


    public RespBeanPage getEmpByPage(Integer page, Integer size, Employee employee, Date[] beginDateScope) {
        if (page != null && size != null && page != 0 && size != 0) {
            // 获取当前页数是第几行数据
            page = (page - 1) * size;
        }
        // 分页查询以及搜索
        List<Employee> list = employeeMapper.getEmpByPage(page, size, employee, beginDateScope);
        // 查询总记录数
        Long total = employeeMapper.getTotal(employee, beginDateScope);
        RespBeanPage beanPage = new RespBeanPage();
        beanPage.setData(list);
        beanPage.setTotal(total);
        return beanPage;
    }

    public int addEmp(Employee employee) {
        int result = employeeMapper.insertSelective(employee);
        if (result == 1) {
            // 根据刚插入的员工ID 查询员工的所有数据（主要原因是，employee 表中保存的是职位id,而需要的是职位名）
            // 注意这里需要刚插入数 sql 语句实现主键回填
            Employee emp = employeeMapper.getEmployeeById(employee.getId());
            // 日志打印
            logger.info("service: " + emp.toString());
            // 将员工信息发送，参数1：消息队列的名称 ，参数2：消息队列的内容
            rabbitTemplate.convertAndSend("anyCcCN.mail.welcome", emp);

        }
        return result;
    }

    public int maxWorkID() {
        return employeeMapper.maxWorkID();
    }

    public int deleteEmpById(Integer id) {
        return employeeMapper.deleteByPrimaryKey(id);
    }

    public int updateEmp(Employee employee) {
        return employeeMapper.updateByPrimaryKeySelective(employee);
    }

    public int addEmps(List<Employee> list) {
        return employeeMapper.addEmps(list);
    }

    public RespBeanPage getEmployeeByPageWithSalary(Integer page, Integer size) {
        if (page != null && size != null) {
            page = (page -1) * size;
        }
        List<Employee> list = employeeMapper.getEmployeeByPageWithSalary(page,size);
        RespBeanPage respBeanPage = new RespBeanPage();
        respBeanPage.setData(list);
        respBeanPage.setTotal(employeeMapper.getTotal(null,null));
        return respBeanPage;
    }

    public Integer updateEmployeeSalaryById(Integer eid, Integer sid) {
        return employeeMapper.updateEmployeeSalaryById(eid,sid);
    }
}
